﻿namespace Possan.Localization.Scanner
{
	public class CSharpRowParser
	{
		public string Line { get; set; }

		public string FoundID { get; set; }

		public string FoundNamespace { get; set; }
		public bool ThisNamespace { get; set; }

		public string FoundPhrase { get; set; }

		public string FoundFallbackPhrase { get; set; }

		public CSharpRowParser()
		{
			Line = "";
			FoundID = "";
			FoundNamespace = "";
			ThisNamespace = false;
			FoundPhrase = "";
			FoundFallbackPhrase = "";
		}

		public CSharpRowParser(string line)
			: this()
		{
			Line = line;
		}

		public bool Parse()
		{
			bool ok = false;

			string code = Line;

			code = CodeScanner.RemoveMultilineComments(code);

			var tokenizer = new CSharpTokenizer(code);

			string cmd = tokenizer.ReadText('(');
			tokenizer.SkipWhitespace('(');

			string type = tokenizer.ReadText(',');
			if (type == "this")
			{
				ThisNamespace = true;
			}
			else
			{
				var typetok = new CSharpTokenizer(type);
				string typeofcall = typetok.ReadText('(').ToLower();
				typetok.SkipWhitespace('(');
				if (typeofcall == "typeof")
				{
					FoundNamespace = typetok.ReadText(')');
				}
				else if (typeofcall == "this.gettype")
				{
					ThisNamespace = true;
				}
				else if (typeofcall == "gettype")
				{
					ThisNamespace = true;
				}
				else if (typeofcall == "type.gettype")
				{
					FoundNamespace = typetok.ReadText(')').Trim(new[] { '\"' });
				}
				tokenizer.SkipWhitespace(')');
			}

			tokenizer.SkipWhitespace(',');

			if (cmd == "Translate.ID")
			{
				FoundID = tokenizer.ReadCSharpStringValue();
				tokenizer.SkipWhitespace(',');

				FoundFallbackPhrase = tokenizer.ReadCSharpStringValue();

				ok = true;
			}
			else if (cmd == "Translate.Phrase")
			{
				FoundPhrase = tokenizer.ReadCSharpStringValue();
				tokenizer.SkipWhitespace(',');

				ok = true;
			}

			return ok;
		}
	}
}
